﻿using BLL.Base;
using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.ViewEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BLL
{
    public class InventoryBLL : PubMethod
    {
        Commands cmd;
        LoginInfo userLogin;
        Tools.TxtLogHelper txt;
        ReturnResult rsl;
        List<OperateModel> operList;

        public InventoryBLL()
        {
            cmd = new Commands();
            userLogin = new LoginInfo();
            txt = new Tools.TxtLogHelper();
        }
        /// <summary>
        /// 生产盘点任务列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getInventoryTaskList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0 ");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                        }
                    }
                }
                var list = cmd.PageList<ViewInventoryTask>("V_InventoryTask", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                //var list = cmd.PageList<ViewInventoryTask>("V_InventoryTask_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 盘点报表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getInventoryReports(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(" 1=1 ");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "isDone")
                            {
                                sb.Append("venCode in(");
                                sb.Append("select distinct venCode from ven_inventoryTask_reportDiffer where ");
                                if (obj.Value.ToString() == "1")
                                {
                                    sb.Append("done='1')");
                                }
                                else
                                {
                                    sb.Append("done='0')");
                                }
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }

                        }
                    }
                }
                var list = cmd.PageList<ViewInventoryTaskReport>("V_InventoryTask_report", pageIndex, pageSize, sb.ToString(), "rDatetime desc", ref pageCount);

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 保存盘点任务
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult SaveInventoryTask(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                #region 防空值
                if (string.IsNullOrWhiteSpace(json["rDatetime"].ToString()))
                {
                    rsl.Message = "盘点日期不允许为空";
                    return rsl;
                }

                if (string.IsNullOrWhiteSpace(json["wareHouse"].ToString()))
                {
                    rsl.Message = "盘点仓库不允许为空";
                    return rsl;
                }
                #endregion

                List<string> sqlList = new List<string>();
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from ven_inventoryTask_Info where ");
                sb.Append(" wareHouse='" + json["wareHouse"].ToString() + "' and status='ING' and isDel=0");
                var taskTable = cmd.GetDataTable(sb.ToString());
                if (string.IsNullOrWhiteSpace(json["proCode"].ToString()))
                {
                    #region 如果盘点存货为空，则系统默认为整个仓库进行盘点

                    if (taskTable.Rows.Count > 0)
                    {
                        rsl.Message = string.Format("任务存在重复，禁止创建新盘点任务：{0}", json["wareHouse"].ToString());
                        return rsl;
                    }
                    string vCode = CreateCodeInfo("V", "盘点编码", 3);
                    sb.Clear();
                    sb.Append("insert into ven_inventoryTask_Info ");
                    sb.Append("(rDatetime,createtime,createuser,status,wareHouse,");
                    sb.Append("proCode,types,isLock,venCode,proName,isDel,spec) values(");
                    sb.Append("'" + json["rDatetime"].ToString() + "','" + getNow() + "',");
                    sb.Append("'" + userLogin.UserInfo().userCode + "','ING','" + json["wareHouse"].ToString() + "',");
                    sb.Append("'','wareVen',");
                    sb.Append("1,'" + vCode + "','',0,'" + json["spec"].ToString() + "')");
                    sqlList.Add(sb.ToString());
                    sb.Clear();
                    sb.Append("insert into ven_inventoryTask_datas");
                    sb.Append(" (barCode,proCode,proName,spec,wareHouse,position,number,createtime,dataId,venCode) ");
                    sb.Append("select barCode,proCode,proName,spec,wareHouse,'',1,'" + getNow() + "',");
                    sb.Append("id,'" + vCode + "'");
                    sb.Append(" from V_VenTaskBarData where ");
                    sb.Append(" barStatus='need-out' and bstatus='open' and wareHouse='" + json["wareHouse"] + "'");
                    sb.Append(" and baseCode='" + userLogin.UserInfo().baseCode + "'");
                    sqlList.Add(sb.ToString());

                    #endregion
                }
                else
                {
                    #region 存在存货编码，则按照仓库存货进行盘点

                    foreach (DataRow r in taskTable.Rows)
                    {
                        if (r["types"].ToString().Trim() == "wareVen")
                        {
                            if (r["wareHouse"].ToString() == json["wareHouse"].ToString())
                            {
                                rsl.Message = string.Format("盘点任务重叠，禁止创建任务：{0}", r["wareHouse"].ToString());
                                return rsl;
                            }
                        }

                    }



                    var proArr = json["proCode"].ToString().Split(',');
                    var nameArr = json["proName"].ToString().Split(',');
                    for (int i = 0; i < proArr.Length; i++)
                    {
                        #region 重复任务验证
                        sb.Clear();
                        foreach (DataRow r in taskTable.Rows)
                        {
                            if (r["proCode"].ToString() == proArr[i].Trim())
                            {
                                rsl.Message = string.Format("存货盘点任务已存在：{0}({1})", nameArr[i], proArr[i]);
                                return rsl;
                            }
                        }

                        #endregion
                        string vCode = CreateCodeInfo("V", "盘点编码", 3);
                        sb.Clear();
                        sb.Append("insert into ven_inventoryTask_Info ");
                        sb.Append("(rDatetime,createtime,createuser,status,wareHouse,");
                        sb.Append("proCode,types,isLock,venCode,proName,isDel,spec) values(");
                        sb.Append("'" + json["rDatetime"].ToString() + "','" + getNow() + "',");
                        sb.Append("'" + userLogin.UserInfo().userCode + "','ING','" + json["wareHouse"].ToString() + "',");
                        sb.Append("'" + proArr[i] + "','" + json["types"].ToString() + "',");
                        sb.Append("1,'" + vCode + "','" + nameArr[i].ToString() + "',0,'" + json["spec"].ToString() + "')");
                        sqlList.Add(sb.ToString());
                        sb = new StringBuilder();
                        sb.Append("insert into ven_inventoryTask_datas");
                        sb.Append(" (barCode,proCode,proName,wareHouse,position,number,status,createtime,");
                        sb.Append("dataId,fatherCode,venCode,pici,spec) ");
                        sb.Append("select barCode,proCode,proName,wareHouse,'',1,status,'" + getNow() + "',");
                        sb.Append("id,boxCode,'" + vCode + "','',spec");
                        sb.Append(" from V_BarCode_Info where proCode='" + json["proCode"].ToString() + "' ");
                        sb.Append(" and barStatus='need-out' and status='Y' and wareHouse='" + json["wareHouse"] + "'");
                        // sb.Append(" and baseCode='" + userLogin.UserInfo().baseCode + "'");
                        sqlList.Add(sb.ToString());
                    }
                    #endregion
                }

                if (sqlList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(sqlList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 根据盘点编码获取盘点清单
        /// </summary>
        /// <param name="venCode">盘点编码</param>
        /// <returns></returns>
        public ReturnResult getVenListByCode(string venCode, string condition, string reType)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(venCode))
                {
                    rsl.Message = "盘点编码获取失败";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                if (!string.IsNullOrWhiteSpace(reType))
                {
                    if (reType.Equals("venList"))
                    {
                        sb.Append("select * from ven_inventoryTask_datas where ");
                        sb.Append(" venCode='" + venCode + "' ");
                    }
                    else
                    {
                        sb.Append("select distinct r.barCode,b.proCode,b.proName,b.spec from ven_inventoryTask_records r ");
                        sb.Append("inner join V_BarCode_Info b on b.barcode=r.barCode ");
                        sb.Append(" where venCode='" + venCode + "' ");
                    }

                    if (!string.IsNullOrWhiteSpace(condition))
                    {
                        var json = JsonConvert.DeserializeObject<JObject>(condition);
                        foreach (JProperty obj in json.Properties())
                        {
                            if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                            {
                                if (!string.IsNullOrWhiteSpace(sb.ToString()))
                                {
                                    sb.Append(" and ");
                                }
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                        }
                    }

                    rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                    rsl.Result = true;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取全部有效的盘点任务(移动端)
        /// </summary>
        /// <returns></returns>
        public ReturnResult VenTaskInfo()
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select  venCode, tCode,  tName,spec from V_InventoryTask_info  ");
                sb.Append(" where isDel=0 and status='ING'");
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 盘点记录信息保存(移动端H5)
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult AddTaskRecord(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                List<OperateModel> list = new List<OperateModel>();
                OperateModel oper;
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                //if (string.IsNullOrWhiteSpace(json["wareHouse"].ToString()))
                //{
                //    rsl.Message = "盘点仓库不能为空";
                //    return rsl;
                //}
                if (string.IsNullOrWhiteSpace(json["pchCode"].ToString()))
                {
                    rsl.Message = "盘点编码不能为空";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();

                #region 盘点编码验证
                sb.Append("select *,erpProCode proCode from pCh_CheckTask_info where ");
                sb.Append("pchCode='" + json["pchCode"].ToString() + "' and ");
                sb.Append("isdel=0 and status='pct-doing' and venCode='" + json["pdCode"].ToString() + "' ");
                var venTable = cmd.GetDataTable(sb.ToString());
                if (venTable.Rows.Count < 1)
                {
                    rsl.Message = "盘点单号无效";
                    return rsl;
                }
                #endregion

                #region 重复盘点
                sb.Clear();
                sb.Append("select barCode from pCh_CheckTask_records where ");
                sb.Append(" pchCode='" + json["pchCode"].ToString() + "'");
                sb.Append(" and barCode='" + json["barCode"].ToString() + "'");
                var qTable = cmd.GetDataTable(sb.ToString());
                if (qTable.Rows.Count > 0)
                {
                    rsl.Message = "条码已存在记录,禁止重复盘点";
                    return rsl;
                }
                #endregion

                #region 条码信息显示
                sb.Clear();
                sb.Append("select * from bar_ProductBoxCode_info where barCode='" + json["barCode"].ToString() + "'");
                qTable = cmd.GetDataTable(sb.ToString());
                DbCheckTaskRecords re;
                List<Dictionary<string, string>> barList = new List<Dictionary<string, string>>();
                if (qTable.Rows.Count < 1)
                {
                    #region 非箱码
                    sb.Clear();
                    sb.Append("select * from bar_ProductBarCode_info where barCode='" + json["barCode"].ToString() + "'");
                    var barTable = cmd.GetDataTable(sb.ToString());
                    if (barTable.Rows.Count > 0)
                    {
                        //if (!venTable.Rows[0]["wareHouse"].ToString().Equals(barTable.Rows[0]["wareHouse"].ToString()))
                        //{
                        //    rsl.Result = false;
                        //    rsl.Message = "此码不在所盘仓库";
                        //    return rsl;
                        //}
                        if (!string.IsNullOrWhiteSpace(venTable.Rows[0]["proCode"].ToString()))
                        {
                            var arr = barTable.Rows[0]["proCode"].ToString().Split(',');
                            var varr = venTable.Rows[0]["proCode"].ToString().Split(',');
                            if (varr != null && varr.Length > 0)
                            {
                                var flag = false;//是否存在盘点任务里面的存货
                                foreach (var vProCode in varr)
                                {
                                    if (string.IsNullOrWhiteSpace(vProCode))
                                    {
                                        continue;
                                    }
                                    if (arr != null && arr.Length > 0)
                                    {
                                        foreach (var proCode in arr)
                                        {
                                            if (string.IsNullOrWhiteSpace(proCode))
                                            {
                                                continue;
                                            }
                                            if (vProCode.Equals(proCode))
                                            {
                                                flag = true;
                                            }
                                        }

                                    }
                                }
                                if (!flag)
                                {
                                    rsl.Result = false;
                                    rsl.Message = "此码不是所盘存货类型";
                                    return rsl;
                                }
                            }


                        }
                        barList = cmd.TableToDictionary(barTable);
                    }
                    else
                    {
                        rsl.Result = false;
                        rsl.Message = "此码为无效码";
                        return rsl;
                    }
                    #endregion
                }
                else
                {
                    #region 箱码
                    if (qTable.Rows[0]["isFull"].ToString() == "ful")
                    {
                        #region 满箱状态，扫描箱码系统视为箱内条码全部扫描
                        sb.Clear();
                        sb.Append("select * from bar_ProductBarCode_info where boxCode='" + json["barCode"].ToString() + "'");
                        qTable = cmd.GetDataTable(sb.ToString());
                        foreach (DataRow r in qTable.Rows)
                        {
                            re = new DbCheckTaskRecords();
                            //re.venCode = json["venCode"].ToString();
                            //re.wareHouse = json["wareHouse"].ToString();
                            re.status = "Y";
                            re.memo = "Box";//不得随意更改，盘点报告有用到
                            re.Id = Guid.NewGuid().ToString().ToLower().Replace("-", "");
                            re.createuser = json["userCode"].ToString();
                            re.createtime = getNow();
                            re.barCode = r["barCode"].ToString();
                            oper = new OperateModel();
                            oper.Data = re;
                            oper.Types = OperateModel.OperateType.Add;
                            list.Add(oper);
                        }
                        barList = cmd.TableToDictionary(qTable);
                        #endregion
                    }
                    else
                    {
                        rsl.Message = "此箱码非满箱，请扫箱内条码盘点";
                        return rsl;
                    }
                    #endregion
                }
                #endregion

                #region 记录保存
                re = new DbCheckTaskRecords();
                re.pchCode = json["pchCode"].ToString();
                re.barCode = json["barCode"].ToString();
                re.createtime = getNow();
                re.createuser = json["createuser"].ToString();
                re.Id = Guid.NewGuid().ToString().ToLower().Replace("-", "");
                re.status = "Y";
                //re.wareHouse = json["wareHouse"].ToString();
                //re.venCode = json["venCode"].ToString();
                oper = new OperateModel();
                oper.Data = re;
                oper.Types = OperateModel.OperateType.Add;
                list.Add(oper);
                #endregion

                if (list.Count > 0)
                {
                    rsl = cmd.MoreUpdate(list);
                    if (rsl.Result)
                    {
                        sb.Clear();
                        sb.Append("select * from pCh_CheckTask_records where pchCode='" + json["pchCode"].ToString() + "' and status='Y' ");
                        var barTable = cmd.GetDataTable(sb.ToString());
                        var dic = new Dictionary<string, object>();
                        var barNumber = 0;
                        if (barTable != null && barTable.Rows.Count > 0)
                        {
                            barNumber = barTable.Rows.Count;
                        }
                        dic.Add("barNumber", barNumber);
                        rsl.Data = dic;
                    }
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取全部有效的盘点记录(移动端)
        /// </summary>
        /// <returns></returns>
        public ReturnResult getInventoryList(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "传入的参数不能为空";
                    rsl.Result = false;
                    return rsl;
                }
                string barCodes = string.Empty;
                var json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                StringBuilder sb = new StringBuilder();
                var dicList = new Dictionary<string, object>();
                DbCheckTaskRecords venTaskRecord = new DbCheckTaskRecords();
                sb.Append("select barCode from [dbo].[pCh_CheckTask_records] ");
                sb.Append(" where pchCode = '" + json["pchCode"].ToString() + "'");
                var dt = cmd.GetDataTable(sb.ToString());
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow item in dt.Rows)
                    {
                        barCodes += "'" + item[0] + "'" + ",";
                    }
                }
                sb.Clear();
                if (barCodes.Length <= 0)
                {
                    rsl.Message = "无数据";
                    rsl.Result = false;
                    return rsl;
                }
                sb.Append(" select * from bar_ProductBarCode_info");
                sb.Append(" where barCode in(" + barCodes.TrimEnd(',') + ") ");
                dt = cmd.GetDataTable(sb.ToString());
                var list = cmd.TableToDictionary(dt);
                if (json.Property("mobType") != null && !string.IsNullOrWhiteSpace(json["mobType"].ToString()) && json["mobType"].ToString().Equals("H5"))
                {
                    #region 构建列表数据
                    #region 构建列表元素显示格式
                    var headList = new List<object>();
                    var hList = new List<Dictionary<string, string>>();
                    createHead(ref hList, "barCode", "条码号");
                    headList.Add(hList);
                    //hList = new List<Dictionary<string, string>>();
                    //createHead(ref hList, "proCode", "存货编码");
                    //createHead(ref hList, "proName", "存货名称");
                    //headList.Add(hList);
                    hList = new List<Dictionary<string, string>>();
                    //createHead(ref hList, "proStyle", "存货类型");
                    createHead(ref hList, "planCode", "生产计划单");
                    headList.Add(hList);
                    hList = new List<Dictionary<string, string>>();
                    createHead(ref hList, "number", "数量");
                    createHead(ref hList, "proWeight", "重量");
                    headList.Add(hList);
                    hList = new List<Dictionary<string, string>>();
                    createHead(ref hList, "barList", "明细信息");
                    headList.Add(hList);
                    #endregion
                    var listInfo = new Dictionary<string, object>();
                    #region 数据分页显示
                    //总条数
                    var pageCount = "0";
                    //总页数
                    var pageNumber = "0";
                    //每页条数
                    var pageSize = "20";
                    var paraList = cmd.getParam("appPageSize");
                    if (paraList != null && paraList.Count > 0)
                    {
                        if (!string.IsNullOrWhiteSpace(paraList[0].parValue))
                        {
                            pageSize = paraList[0].parValue;
                        }
                    }
                    var table = cmd.PageTableList(dt, json["pageIndex"].ToString(), pageSize, ref pageCount, ref pageNumber);
                    table.Columns.Add("barList");
                    var listDt = new DataTable();
                    #region 获取条码子表数据
                    if (table != null && table.Rows.Count > 0)
                    {
                        barCodes = "";
                        foreach (DataRow r in table.Rows)
                        {
                            barCodes += "'" + r["barCode"].ToString() + "'" + ",";
                        }
                        sb.Clear();
                        sb.Append("select * from V_BarCode_Sub_Info where 1=1 ");
                        sb.Append(" and barCode in(" + barCodes.TrimEnd(',') + ")");
                        listDt = cmd.GetDataTable(sb.ToString());
                    }
                    #endregion
                    var temlist = cmd.TableToDictionary(table);

                    listInfo.Add("head", headList);
                    listInfo.Add("list", temlist);
                    #region 构建条码表体信息
                    headList = new List<object>();
                    hList = new List<Dictionary<string, string>>();
                    //createHead(ref hList, "proCode", "存货编码");
                    createHead(ref hList, "proName", "存货名称");
                    headList.Add(hList);
                    hList = new List<Dictionary<string, string>>();
                    createHead(ref hList, "number", "数量");
                    createHead(ref hList, "color", "色号");
                    headList.Add(hList);
                    var barMXList = new List<object>();
                    if (temlist != null && temlist.Count > 0)
                    {
                        foreach (var item in temlist)
                        {
                            var tembarCode = item["barCode"].ToString();
                            if (listDt != null && listDt.Rows.Count > 0)
                            {
                                var selectRow = listDt.Select("barCode='" + tembarCode + "'");
                                var listBar = "";
                                var temMxList = new List<object>();
                                if (selectRow != null && selectRow.Length > 0)
                                {
                                    var mxDt = selectRow.CopyToDataTable<DataRow>();
                                    foreach (DataRow mRow in mxDt.Rows)
                                    {
                                        mRow["proName"] = mRow["proName"].ToString() + "(" + mRow["proCode"].ToString() + ")";
                                    }
                                    var temDtList = cmd.TableToDictionary(mxDt);
                                    temMxList.InsertRange(0, temDtList);
                                }
                                barMXList.Add(temMxList);
                            }
                        }
                    }
                    listInfo.Add("mxHead", headList);
                    listInfo.Add("mxList", barMXList);
                    #endregion

                    #endregion

                    listInfo.Add("pageNumber", pageNumber);
                    var pageIndex = int.Parse(json["pageIndex"].ToString());
                    listInfo.Add("pageIndex", pageIndex.ToString());
                    dicList.Add("listInfo", listInfo);
                    #endregion

                    #region 构建汇总数据
                    headList = new List<object>();
                    hList = new List<Dictionary<string, string>>();
                    createHead(ref hList, "count", "总件数");
                    createHead(ref hList, "number", "总数量");
                    headList.Add(hList);
                    hList = new List<Dictionary<string, string>>();
                    createHead(ref hList, "weight", "总重量");
                    headList.Add(hList);
                    #region 汇总列表中信息
                    var sumDic = new Dictionary<string, string>();
                    var number = 0;
                    var count = 0;
                    var weight = 0.0m;
                    var meter = 0.0m;

                    if (list != null && list.Count > 0)
                    {
                        foreach (var item in list)
                        {
                            var proNumber = item["number"].ToString();
                            var proWeight = item["proWeight"].ToString();
                            if (!string.IsNullOrWhiteSpace(proNumber) && Convert.ToDecimal(proNumber) > 0)
                            {
                                number += int.Parse(proNumber);
                            }
                            if (!string.IsNullOrWhiteSpace(proWeight) && Convert.ToDecimal(proWeight) > 0)
                            {
                                weight += Convert.ToDecimal(proWeight);
                            }
                        }
                        count = list.Count;
                    }
                    sumDic.Add("count", count.ToString());
                    sumDic.Add("number", number.ToString());
                    sumDic.Add("weight", Convert.ToDecimal(weight).ToString("F2"));
                    var sumDicList = new List<Dictionary<string, string>>();
                    sumDicList.Add(sumDic);
                    #endregion
                    var sumList = new Dictionary<string, object>();
                    sumList.Add("head", headList);
                    sumList.Add("list", sumDicList);
                    dicList.Add("sumList", sumList);
                    #endregion
                }
                rsl.Data = dicList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Result = false;
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 生成盘点报告
        /// </summary>
        /// <param name="venCodes"></param>
        /// <returns></returns>
        public ReturnResult createReport(string venCodes)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                OperateModel oper = new OperateModel();
                if (string.IsNullOrWhiteSpace(venCodes))
                {
                    rsl.Message = "关键参数丢失";
                    return rsl;
                }
                var arr = venCodes.Split(',');
                List<Dictionary<string, string>> reportList = new List<Dictionary<string, string>>();
                foreach (string code in arr)
                {
                    if (!string.IsNullOrWhiteSpace(code))
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append("select * from ven_inventoryTask_Info where ");
                        sb.Append(" venCode='" + code + "'");
                        var taskTable = cmd.GetDataTable(sb.ToString());//获取盘点任务信息
                        if (operList.Count > 0)
                        {
                            rsl = cmd.MoreUpdate(operList);

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 盘点报告差异表
        /// </summary>
        /// <param name="datas">数据</param>
        /// <param name="yk">盘盈盘亏</param>
        /// <param name="btype">箱码、条码</param>
        /// <param name="venCode">盘点编码</param>
        /// <param name="list">数据集合</param>
        private void createVenDiffer(string datas, string yk, string btype, string venCode, ref List<OperateModel> list)
        {
            var dArr = datas.TrimEnd(',').Split(',');
            OperateModel oper;
            foreach (string str in dArr)
            {
                DbCheckTaskReportDiffer diff = new DbCheckTaskReportDiffer();
                diff.barCode = str;
                diff.done = "0";
                diff.types = yk;

                diff.barType = btype;
                oper = new OperateModel();
                oper.Data = diff;
                oper.Types = OperateModel.OperateType.Add;
                list.Add(oper);
            }
        }
        /// <summary>
        /// 获取盘点差异数据
        /// </summary>
        /// <param name="venCode">盘点任务编码</param>
        /// <param name="barType">条码类型(1箱码 0条码)</param>
        /// <param name="types">盈亏类型(1盈 0亏)</param>
        /// <returns></returns>
        public ReturnResult getReportDiffer(string venCode, string barType, string types)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from ven_inventoryTask_reportDiffer where ");
                sb.Append(" venCode='" + venCode + "' and barType='" + barType + "' ");
                sb.Append("and types='" + types + "'");
                var list = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i]["done"] == "0")
                    {
                        list[i]["done"] = "未处理";
                    }
                    else
                    {
                        list[i]["done"] = "已处理";
                    }
                }
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 更新盘点差异数据信息
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="barType"></param>
        /// <param name="entryType"></param>
        /// <returns></returns>
        public ReturnResult DoVenDiffer(string ids, string barType, string entryType)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                List<string> sqlList = new List<string>();
                sb.Append("select wareHouse from ven_inventoryTask_Info where venCode in (");
                sb.Append("select distinct venCode from ven_inventoryTask_reportDiffer where id in(" + ids + "))");
                var vTable = cmd.GetDataTable(sb.ToString());
                string wareCode = "0";
                if (vTable.Rows.Count > 0)
                {
                    wareCode = vTable.Rows[0]["wareHouse"].ToString();
                }
                sb.Clear();
                sb.Append("update ven_inventoryTask_reportDiffer set done='1'");
                sb.Append(",memo='" + string.Format("{0}({1})", getNow(), userLogin.UserInfo().userCode) + "'");
                sb.Append(" where id in(" + ids + ")");
                sqlList.Add(sb.ToString());

                #region 条码
                sb = new StringBuilder();
                sb.Append("update bar_ProductBarCode_info set wareHouse='" + wareCode + "',");
                if (entryType == "1")
                {
                    sb.Append("barStatus='need-out' ");
                }
                else
                {
                    sb.Append("barStatus='bar-finish' ");
                }
                sb.Append(" where barCode in(select barCode from ven_inventoryTask_reportDiffer");
                sb.Append(" where id in(" + ids + "))");
                sqlList.Add(sb.ToString());
                #endregion

                rsl = cmd.MoreUpdate(sqlList);
                if (rsl.Result)
                {
                    txt.AddLogMsg("差异数据操作：" + JsonConvert.SerializeObject(sqlList));
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取盘点仓库的所有存货
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <param name="wareCode"></param>
        /// <returns></returns>
        public ReturnResult getInventoryProduct(string pageIndex, string pageSize, ref string pageCount, string condition, string wareCode)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(" wareHouse='" + wareCode + "' and baseCode='" + userLogin.UserInfo().baseCode + "' ");
                sb = CreateSelectCondition(sb, condition);
                var list = cmd.PageList<ViewInventoryProduct>("V_InventoryProduct_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }
}
